package br.com.post.persistence;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.Profile;

public class ProfileDao {
	private static ProfileDao instance;
	/**
	 * Persiste perfil no banco
	 * @param profile
	 */
	public void createProfile(Profile profile) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(profile);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza o perfil no banco
	 * @param profile
	 */
	public void updateProfile(Profile profile) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(profile);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona um perfil no banco de acordo com o id(long)
	 * @param profile_id
	 * @return profile
	 */
	public Profile selectProfile(long profile_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Profile profile = (Profile)session.get(Profile.class,profile_id);
		tx.commit();
		session.close();
		return profile;
	}
	
	/**
	 * Deleta o perfil de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove o perfil selecionado
	 * @param profile_id
	 */
	public void deleteProfile(long profile_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Profile profile = selectProfile(profile_id);
		session.delete(profile);
		tx.commit();
		session.close();
	}
	/**
	 * Retorna o profile com a lista completa de users populada
	 * @param profile_id
	 * @return
	 */
	public Profile selectProfileWithUsers(long profile_id){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery("from Profile p join fetch p.profile_list_user where p.profile_id = ?");
		query.setLong(0,profile_id);
		Profile profile = (Profile) query.uniqueResult();
		tx.commit();
		session.close();
		return profile; 
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Profile> getList(){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery("from Profile p order by p.profile_name");
		List<Profile> listprofile = query.list(); 
		tx.commit();
		session.close();
		return listprofile;
	}
	
	public static ProfileDao getInstance() {
		if(instance == null)
			instance = new ProfileDao();
		return instance;
	}

	public static void setInstance(ProfileDao instance) {
		ProfileDao.instance = instance;
	}
	
}

